<?php
// +----------------------------------------------------------------------
// | 萤火商城系统 [ 致力于通过产品和服务，帮助商家高效化开拓市场 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2017~2023 https://www.yiovo.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed 这不是一个自由软件，不允许对程序代码以任何形式任何目的的再发行
// +----------------------------------------------------------------------
// | Author: 萤火科技 <admin@yiovo.com>
// +----------------------------------------------------------------------
declare (strict_types = 1);

namespace app\store\model\ding;

use app\common\model\ding\Seat as SeatModel;
use app\common\service\store\User as UserService;
use think\facade\Db;

/**
 * 文章模型
 * Class Seat
 * @package app\store\model
 */
class Seat extends SeatModel
{

    //预订管理
    public function getListOrder(array $params = [])
    {
        if ($params['date'] == '') {
            $params['date'] = date('Y-m-d');
        } else {

            $dd = explode('T', $params['date']);
            if (count($dd) > 1) {
                $dd2            = explode(';', $dd[0]);
                $params['date'] = $dd2 ? $dd2[1] : $params['date'];
                $params['date'] = Date('Y-m-d', strtotime($params['date']) + 86400);
            }

        }

        $store_shop_id = UserService::getLoginInfo()['user']['shop_id'];
        if ($store_shop_id > 0) {
            $shopId = $store_shop_id;
        } else {
            $shopId = $params['shopId'];
        }

        $filter = [];
        $where  = [];
        if ($params['status'] == 'all') {

        }
        if ($params['status'] == 'yuding') {

            //ids
            $seatIds = Db::name('ding_seat')
                ->where('shop_id', $shopId)
                ->where('category_id', $params['categoryId'])
                ->where('status', '>', 0)
                ->field('seat_id')->select()->toArray();
            $seatIds  = array_column($seatIds, 'seat_id');
            $orderIds = Db::name('ding_order_seat')
                ->where('status', 'in', [10, 20])
                ->where('date', $params['date'])
                ->where('type', $params['type'])
                ->field('seat_id')
                ->select()->toArray();
            $orderIds = array_column($orderIds, 'seat_id');

            $ids = array_merge($seatIds, $orderIds);

            $filter[] = ['seat_id', 'in', $ids];

        }

        //占座

        $seatIds = Db::name('ding_seat_lock')
            ->where('shop_id', $shopId)
            ->where('date', $params['date'])
            ->where('type', $params['type'])
            ->field('seat_id')->select()->toArray();
        $seatIds = array_column($seatIds, 'seat_id');

        //预定座位
        $orderIds = Db::name('ding_order_seat')
            ->where('status', 'in', [10, 20])
            ->where('date', $params['date'])
            ->where('type', $params['type'])
            ->field('seat_id')
            ->select()->toArray();
        $orderIds = array_column($orderIds, 'seat_id');

        if ($params['status'] == 'zhanyong') {

            $filter[] = ['seat_id', 'in', $seatIds];

        }

        if ($params['status'] == 'kong') {

            $ids      = array_merge($seatIds, $orderIds);
            $filter[] = ['seat_id', 'not in', $ids];

        }
        $seats = Db::name('ding_seat')
            ->where('shop_id', $shopId)
            ->where('category_id', $params['categoryId'])
            ->where($filter)
            ->field('*,status as seat_status')->select()->toArray();

        foreach ($seats as $k => $value) {
            $status = $value['status'];
            if (in_array($value['seat_id'], $seatIds)) {
                //占座
                $status = 30;
            }

            $order = Db::name('ding_order_seat')->alias('o')

                ->join('ding_letter l', 'l.type_id=o.letter_type')
                ->join('ding_order order', 'order.id=o.order_id')
                ->where('o.seat_id', $value['seat_id'])
                ->where($where)
                ->where('o.date', $params['date'])
                ->where('order.type', $params['type'])
                ->where('o.is_delete', 0)
                ->where('o.status', '<>', 30)
                ->field('o.*,l.type_id as letter_type,order.real_name,order.sex,order.mobile,order.to_people,
						order.source,order.member_id,order.week,order.sex,order.remark')
                ->find();

            $seats[$k]['status'] = $order ? $order['status'] : $status;
            $is_past             = 0;

            if ($order) {
                if ($order['clerk_id'] > 0) {

                    $clerk                   = Db::name('store_shop_clerk')->where('clerk_id', $order['clerk_id'])->find();
                    $seats[$k]['clerk_name'] = $clerk['real_name'];
                }
                $member = Db::name('ding_clerk_member')->where('shop_id', $order['shop_id'])->where('mobile', $order['mobile'])->find();

                $seats[$k]['order_id']    = $order['order_id'];
                $seats[$k]['mobile']      = $order['mobile'];
                $seats[$k]['sex']         = $order['sex'];
                $seats[$k]['to_people']   = $order['to_people'];
                $seats[$k]['real_name']   = $order['real_name'];
                $seats[$k]['letter_type'] = $order['letter_type'];
                $seats[$k]['source']      = $order['source'];
                $seats[$k]['time']        = $order['time'];
                $seats[$k]['sex']         = $order['sex'];
                $seats[$k]['week']        = $order['week'];
                $seats[$k]['date']        = $order['date'];
                $seats[$k]['clerk_id']    = $order['clerk_id'];
                $seats[$k]['type']        = $order['type'];
                $seats[$k]['member_id']   = $order['member_id'];
                $seats[$k]['member']      = $member;
                $seats[$k]['is_lian']     = $order['is_lian'];
                $seats[$k]['remark']      = $order['remark'];
                $time                     = strtotime($order['date'] . ' ' . $order['time']);
                if ($time <= time()) {
                    $is_past             = 1;
                    $seats[$k]['status'] = 11;
                }
            }

            $expired = 0;
            if ($order && strtotime($order['date']) < strtotime(date('Y-m-d'))) {

                $expired = 1;
            }

            $seats[$k]['expired'] = $expired; //过期不可操作
            $seats[$k]['is_past'] = $is_past;

        }

        return $seats;
    }
    /**
     * 获取列表
     * @param array $param
     * @return \think\Paginator
     * @throws \think\db\exception\DbException
     */
    public function getList(array $param = [])
    {
        // 查询参数
        $params = $this->setQueryDefaultValue($param, [
            'title'   => '', // 文章标题
            'shop_id' => 0,  // 文章分类id
            'status'  => -1, // 文章状态
        ]);
        // 检索查询条件
        $filter = [];
        // 文章标题
        ! empty($params['title']) && $filter[] = ['name', 'like', "%{$params['name']}%"];
        // 文章分类id
        $params['shop_id'] > 0 && $filter[] = ['shop_id', '=', $params['shop_id']];
        // 文章状态
        $params['status'] > -1 && $filter[] = ['status', '=', $params['status']];
        $store_user                         = UserService::getLoginInfo();
        if ($store_user['user']['shop_id'] > 0) {

            $filter[] = ['shop_id', '=', $store_user['user']['shop_id']];
        }

        // 查询列表数据
        return $this->with(['image', 'shop'])

            ->where($filter)

            ->order(['sort' => 'asc', 'create_time' => 'desc'])
            ->paginate(15);
    }
    public function getListAll(array $param = [])
    {
        // 查询参数
        $params = $this->setQueryDefaultValue($param, [
            'title'      => '', // 文章标题
            'shop_id'    => 0,  // 文章分类id
            'status'     => -1, // 文章状态
            'categoryId' => -1, // 文章状态
        ]);
        // 检索查询条件
        $filter = [];
        // 文章标题
        ! empty($params['title']) && $filter[] = ['name', 'like', "%{$params['title']}%"];
        // 文章分类id
        $params['shop_id'] > 0 && $filter[] = ['shop_id', '=', $params['shop_id']];
        // 文章状态
        $params['status'] > -1 && $filter[]     = ['status', '=', $params['status']];
        $params['categoryId'] > -1 && $filter[] = ['category_id', '=', $params['categoryId']];
        $store_user                             = UserService::getLoginInfo();
        if ($store_user['user']['shop_id'] > 0) {

            $filter[] = ['shop_id', '=', $store_user['user']['shop_id']];
        }

        // 查询列表数据
        $list = $this

            ->where($filter)
            ->select()->toArray();
        $date = Date('Y-m-d');

        foreach ($list as $key => $value) {
            $seat = Db::name('ding_order_seat')
                ->where('date', $date)
                ->where('seat_id', $value['seat_id'])->where('status', '<', 30)->field('status')->find();
            if ($seat) {
                if ($seat['status'] == 10) {
                    $list[$key]['status']      = 30;
                    $list[$key]['status_text'] = '预订';
                }
                if ($seat['status'] == 20) {
                    $list[$key]['status']      = 40;
                    $list[$key]['status_text'] = '用餐';
                }
            }
            $list[$key]['order_seat'] = $seat;

        }

        return $list;
    }
    /**
     * 新增记录
     * @param array $data
     * @return false|int
     */
    public function add(array $data)
    {

        $store_user = UserService::getLoginInfo();
        if ($store_user['user']['shop_id'] > 0) {
            $data['shop_id'] = $store_user['user']['shop_id'];
        }

        $data['store_id'] = self::$storeId;
        return $this->save($data);
    }
    //占座，解锁
    public function lock(array $data)
    {
        if ($data['status'] == 30) {
            $lock['date']        = $data['date'];
            $lock['shop_id']     = $data['shopId'];
            $lock['type']        = $data['type'];
            $lock['seat_id']     = $data['seatId'];
            $lock['name']        = $data['name'];
            $lock['create_time'] = time();
            $lock['store_id']    = self::$storeId;
            Db::name('ding_seat_lock')->insert($lock);
        } else {
            Db::name('ding_seat_lock')
                ->where('shop_id', $data['shopId'])
                ->where('seat_id', $data['seatId'])
                ->where('date', $data['date'])
                ->where('type', $data['type'])
                ->delete();
        }

        return true;
    }

    /**
     * 更新记录
     * @param array $data
     * @return bool|int
     */
    public function edit(array $data)
    {

        return $this->save($data) !== false;
    }

    /**
     * 软删除
     * @return false|int
     */
    public function setDelete()
    {
        return $this->delete();
    }

    /**
     * 获取文章总数量
     * @param array $where
     * @return int|string
     */
    public static function getSeatTotal(array $where = [])
    {
        return (new static )->where($where)->where('is_delete', '=', 0)->count();
    }

}
